package com.nebula.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.nebula.dao.impl.QaDaoImpl;
import com.nebula.common.PageResult;
import com.nebula.dao.IQaDao;
import com.nebula.entity.Qa;
import com.nebula.service.IQaService;
import com.nebula.util.DateTimeUtil;
import com.nebula.vo.QaVo;

/**
 * @author CcccX
 */
public class QaServiceImpl implements IQaService {
    private IQaDao qaDao = new QaDaoImpl();

    @Override
    public PageResult<QaVo> findByPage(Integer page, Integer size) {
        List<Qa> list = qaDao.findByPage(page, size);
        List<QaVo> qaVos = new ArrayList<QaVo>();
        for (Qa qa : list) {
            QaVo qaVo = assembleQaVo(qa);
            qaVos.add(qaVo);
        }
        //封装PageResult
        PageResult<QaVo> pageResult = new PageResult<>();
        pageResult.setCurrPage(page);
        pageResult.setList(qaVos);
        Integer totalCount = qaDao.selectCount("Qa");
        Double dc = Math.ceil(totalCount.doubleValue() / size);
        pageResult.setTotalCount(totalCount);
        pageResult.setPageSize(dc.intValue());

        return pageResult;
    }

    @Override
    public int save(Qa qa) {
        return qaDao.save(qa);
    }

    @Override
    public Qa findById(int id) {
        return qaDao.findById(id);
    }

    @Override
    public List<Qa> findByIds(Integer[] ids) {
        return qaDao.findByIds(ids);
    }

    @Override
    public int update(Qa qa) {
        return qaDao.update(qa);
    }

    @Override
    public int delete(int id) {
        return qaDao.delete(id);
    }

    @Override
    public List<QaVo> findAll() {
        List<Qa> list = qaDao.findAll();
        List<QaVo> qaVos = new ArrayList<>();
        for (Qa qa : list) {
            QaVo qaVo = assembleQaVo(qa);
            qaVos.add(qaVo);
        }
        return qaVos;
    }

    private QaVo assembleQaVo(Qa qa) {
        QaVo qaVo = new QaVo();

        qaVo.setId(qa.getId());
        qaVo.setQuestion(qa.getQuestion());
        qaVo.setCreatedTime(DateTimeUtil.dateToStr(qa.getCreatedTime()));
        qaVo.setUpdatedTime(DateTimeUtil.dateToStr(qa.getUpdatedTime()));

        return qaVo;
    }
}
